package com.boss.controller;

import com.alibaba.fastjson2.JSON;
import com.boss.service.WebSocketSessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
import java.time.LocalDateTime;
import java.util.Map;

import static com.boss.service.WebSocketSessionService.SESSION_POOL;

@Component
@Slf4j
public class WebSocketHandler extends AbstractWebSocketHandler {
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        // 在收到消息后，将消息广播给所有连接到服务器的客户端
        String messageStr = message.getPayload().toString();
        System.out.println(session.getRemoteAddress() + " 发送消息：" + messageStr);
        for (Map.Entry<String, WebSocketSession> entry : SESSION_POOL.entrySet()) {
            if (!entry.getValue().getId().equals(session.getId())) {
                handleJsonMessage(entry.getValue(), new TextMessage(messageStr));
            }
        }
    }
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info(session.getId() + "建立ws连接");
        WebSocketSessionService.add(session.getId(), session);
        session.sendMessage(new TextMessage(session.getId() + "建立ws连接！"));
    }
    protected void handleJsonMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("发送Json消息");
        // 获得客户端传来的消息
        String messageStr = message.getPayload();
        Object messageString = JSON.parseObject(messageStr);
        session.sendMessage(new TextMessage(messageString.toString()));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("发送文本消息");
        // 获得客户端传来的消息
        String payload = message.getPayload();
        log.info("server 接收到消息 " + payload);
        session.sendMessage(new TextMessage("server 发送给的消息 " + payload + "，发送时间:" + LocalDateTime.now().toString()));
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        log.info("发送二进制消息");
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("异常处理");
        WebSocketSessionService.removeAndClose(session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("关闭ws连接");
        WebSocketSessionService.removeAndClose(session.getId());
    }
}